package com.cq.hd.app.controller;

import com.cq.hd.app.biz.OrderBiz;
import com.cq.hd.app.biz.QrCodeBiz;
import com.cq.hd.app.dto.OrderExportDto;
import com.cq.hd.common.annotation.LoginUser;
import com.cq.hd.common.entity.AppLoginUser;
import com.cq.hd.common.entity.BusinessInfo;
import com.cq.hd.common.entity.UserInfo;
import com.cq.hd.common.enums.biz.ActiveTypeEnum;
import com.cq.hd.common.enums.biz.OrderSelectTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Result;
import com.cq.hd.common.response.ResultGenerator;
import com.cq.hd.common.response.Throw;
import com.cq.hd.order.api.TbOrderApi;
import com.cq.hd.order.api.dto.*;
import com.cq.hd.order.api.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/order")
@Api(tags = "订单相关接口")
@Slf4j
public class OrderController {

    @Autowired
    private TbOrderApi orderApi;

    @Autowired
    private QrCodeBiz qrCodeBiz;

    @Autowired
    private OrderBiz orderBiz;

    @ApiOperation(value = "获取活动红包可用状态")
    @ApiImplicitParam(name = "activeId", value = "活动id", paramType = "query", dataType = "Long")
    @GetMapping("/getRedAvailableStatus")
    public Result<Boolean> getRedAvailableStatus(Long activeId, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        if (activeId == null || activeId <= 0) {
            Throw.isBusinessException("请选择活动");
        }
        return orderApi.getRedAvailableStatus(activeId, appLoginUser.getUserId());
    }

    @ApiOperation(value = "获取用户已下单该活动的数量(选择下单数量需要显示)")
    @ApiImplicitParam(name = "activeId", value = "活动id", paramType = "query", dataType = "Long")
    @GetMapping("/getActiveOrderNum")
    public Result<Integer> getActiveOrderNum(Long activeId, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        return orderApi.getActiveOrderNum(activeId, appLoginUser.getUserId());
    }

    @ApiOperation(value = "导出活动订单")
    @GetMapping("/exportOrder")
    public Result<Object> exportOrder(OrderExportDto orderExportDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser, HttpServletResponse response) {
        Long businessId = 0L;
        UserInfo userInfo = appLoginUser.getUserInfo();
        if (userInfo != null) {
            BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
            if (businessInfo != null) {
                businessId = businessInfo.getId();
            }
        }

        orderExportDto.setUserId(appLoginUser.getUserId());
        orderExportDto.setBusinessId(businessId);
        return orderBiz.exportOrder(orderExportDto, response);
    }

    @ApiOperation(value = "导出积分订单")
    @GetMapping("/exportPointsOrder")
    public Result<Object> exportPointsOrder(OrderExportDto orderExportDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser, HttpServletResponse response) {
        Long businessId = 0L;
        UserInfo userInfo = appLoginUser.getUserInfo();
        if (userInfo != null) {
            BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
            if (businessInfo != null) {
                businessId = businessInfo.getId();
            }
        }

        orderExportDto.setUserId(appLoginUser.getUserId());
        orderExportDto.setBusinessId(businessId);
        orderExportDto.setOrderType(ActiveTypeEnum.POINTS.getValue());
        return orderBiz.exportOrder(orderExportDto, response);
    }

    // 我的活动的订单管理，以及订单管理的统计(有效订单，订单总金额，预估补贴)
    @ApiOperation(value = "我的活动的订单管理的统计")
    @ApiResponse(response = ActiveOrderStatisticsVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/getOrderStatistics")
    public Result<ActiveOrderStatisticsVo> getOrderStatistics(@ApiIgnore @LoginUser AppLoginUser appLoginUser, Long activeId) {
        Long businessId = 0L;
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            businessId = businessInfo.getId();
        }

        return orderApi.getOrderStatistics(businessId, appLoginUser.getUserId(), activeId);
    }

    @ApiOperation(value = "创建订单")
    @ApiImplicitParam(name = "createOrderDto", value = "实体", paramType = "body", dataType = "CreateOrderDto")
    @ApiResponse(response = CreateOrderVo.class, code = 200, message = "接口返回对象参数")
    @PostMapping("/createOrder")
    public Result<CreateOrderVo> createOrder(@RequestBody CreateOrderDto createOrderDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        createOrderDto.setUserId(appLoginUser.getUserId());
        log.error("createOrderDto:{}", createOrderDto);
        return orderApi.createOrder(createOrderDto);
    }

    @ApiOperation(value = "创建拼团订单")
    @ApiImplicitParam(name = "createOrderDto", value = "实体", paramType = "body", dataType = "CreateOrderDto")
    @ApiResponse(response = CreateOrderVo.class, code = 200, message = "接口返回对象参数")
    @PostMapping("/createGroupBuyOrder")
    public Result<CreateOrderVo> createGroupBuyOrder(@RequestBody CreateOrderDto createOrderDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        createOrderDto.setUserId(appLoginUser.getUserId());
        log.info("createOrderDto:{}", createOrderDto);
        return orderApi.createGroupBuyOrder(createOrderDto);
    }

    // 立即支付，根据订单号去调用第三方支付(前期直接修改订单状态为支付成功)
    @ApiOperation(value = "立即支付，唤起第三方支付")
    @ApiImplicitParam(name = "orderPayDto", value = "实体", paramType = "body", dataType = "OrderPayDto")
    @ApiResponse(response = OrderPayVo.class, code = 200, message = "接口返回对象参数")
    @PostMapping("/pay")
    public Result<OrderPayVo> pay(@RequestBody OrderPayDto orderPayDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        orderPayDto.setUserId(appLoginUser.getUserId());
        return orderApi.pay(orderPayDto);
    }

    @ApiOperation(value = "取消支付（用户主动调用）")
    @ApiImplicitParam(name = "cancelPayDto", value = "实体", paramType = "body", dataType = "CancelPayDto")
    @PostMapping("/cancelPay")
    public Result<Boolean> cancelPay(@RequestBody CancelPayDto cancelPayDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        cancelPayDto.setUserId(appLoginUser.getUserId());
        return orderApi.cancelPay(cancelPayDto);
    }

    @ApiOperation(value = "系统取消支付（倒计时到了调用）")
    @ApiImplicitParam(name = "cancelPayDto", value = "实体", paramType = "body", dataType = "CancelPayDto")
    @PostMapping("/systemCancelPay")
    public Result<Boolean> systemCancelPay(@RequestBody CancelPayDto cancelPayDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        cancelPayDto.setUserId(appLoginUser.getUserId());
        return orderApi.systemCancelPay(cancelPayDto);
    }

    @ApiOperation(value = "查单（只要唤醒了第三方支付，关闭第三方支付页面之后，不管是成功还是失败，都要调用）")
    @ApiImplicitParam(name = "orderPayQueryDto", value = "实体", paramType = "body", dataType = "OrderPayQueryDto")
    @PostMapping("/queryOrderPay")
    public Result<Boolean> queryOrderPay(@RequestBody OrderPayQueryDto orderPayQueryDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        orderPayQueryDto.setUserId(appLoginUser.getUserId());
        return orderApi.queryOrderPay(orderPayQueryDto);
    }

    @ApiOperation(value = "去支付")
    @ApiImplicitParam(name = "orderPayQueryDto", value = "实体", paramType = "body", dataType = "OrderPayQueryDto")
    @PostMapping("/toPay")
    public Result<Boolean> toPay(@RequestBody OrderPayQueryDto orderPayQueryDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        orderPayQueryDto.setUserId(appLoginUser.getUserId());
        return orderApi.toPay(orderPayQueryDto);
    }

    @ApiOperation(value = "卖出的订单列表(商家查看)")
    @ApiResponse(response = AppOrderPageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageSellOrder")
    public Result<Page<AppOrderPageVo>> pageSellOrder(AppOrderPageDto appOrderPageDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            appOrderPageDto.setBusinessId(businessInfo.getId());
        }

        appOrderPageDto.setUserId(appLoginUser.getUserId());
        appOrderPageDto.setOrderSelectType(OrderSelectTypeEnum.SELL.getValue());
        return orderApi.pageAppOrder(appOrderPageDto);
    }

    @ApiOperation(value = "分销的订单列表(经纪人查看)")
    @ApiResponse(response = AppOrderPageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageAgentOrder")
    public Result<Page<AppOrderPageVo>> pageAgentOrder(AppOrderPageDto appOrderPageDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            appOrderPageDto.setBusinessId(businessInfo.getId());
        }

        appOrderPageDto.setUserId(appLoginUser.getUserId());
        appOrderPageDto.setOrderSelectType(OrderSelectTypeEnum.AGENT.getValue());
        return orderApi.pageAppOrder(appOrderPageDto);
    }

    @ApiOperation(value = "购买的订单列表(消费者查看)")
    @ApiResponse(response = AppOrderPageVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/pageBuyOrder")
    public Result<Page<AppOrderPageVo>> pageBuyOrder(AppOrderPageDto appOrderPageDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            appOrderPageDto.setBusinessId(businessInfo.getId());
        }

        appOrderPageDto.setUserId(appLoginUser.getUserId());
        appOrderPageDto.setOrderSelectType(OrderSelectTypeEnum.BUY.getValue());
        return orderApi.pageAppOrder(appOrderPageDto);
    }

    @ApiOperation(value = "卖出订单详情(商家查看)")
    @ApiResponse(response = AppOrderDetailVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/sellOrderDetail")
    public Result<AppOrderDetailVo> sellOrderDetail(AppOrderDetailDto appOrderDetailDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            appOrderDetailDto.setBusinessId(businessInfo.getId());
        }

        appOrderDetailDto.setUserId(appLoginUser.getUserId());
        appOrderDetailDto.setOrderSelectType(OrderSelectTypeEnum.SELL.getValue());
        return orderApi.appOrderDetail(appOrderDetailDto);
    }

    @ApiOperation(value = "分销订单详情(经纪人查看)")
    @ApiResponse(response = AppOrderDetailVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/agentOrderDetail")
    public Result<AppOrderDetailVo> agentOrderDetail(AppOrderDetailDto appOrderDetailDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            appOrderDetailDto.setBusinessId(businessInfo.getId());
        }

        appOrderDetailDto.setUserId(appLoginUser.getUserId());
        appOrderDetailDto.setOrderSelectType(OrderSelectTypeEnum.AGENT.getValue());
        return orderApi.appOrderDetail(appOrderDetailDto);
    }

    @ApiOperation(value = "购买订单详情(消费者查看)")
    @ApiResponse(response = AppOrderDetailVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/buyOrderDetail")
    public Result<AppOrderDetailVo> buyOrderDetail(AppOrderDetailDto appOrderDetailDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            appOrderDetailDto.setBusinessId(businessInfo.getId());
        }

        appOrderDetailDto.setUserId(appLoginUser.getUserId());
        appOrderDetailDto.setOrderSelectType(OrderSelectTypeEnum.BUY.getValue());
        return orderApi.appOrderDetail(appOrderDetailDto);
    }

    @ApiOperation(value = "拼团订单详情(消费者查看)")
    @ApiResponse(response = AppGroupBuyOrderDetailVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/groupBuyOrderDetail")
    public Result<AppGroupBuyOrderDetailVo> buyGroupBuyOrderDetail(AppGroupBuyOrderDetailQueryDto param, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        if (appLoginUser == null || appLoginUser.getUserId() == null) {
            Throw.isBusinessException("请先登录");
        }
        param.setUserId(appLoginUser.getUserId());
        return orderApi.appGroupBuyOrderDetail(param);
    }

    @ApiOperation(value = "拼团 - 查看参团成员")
    @ApiResponse(response = GroupBuyMemberVo.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/groupMembers")
    public Result<List<GroupBuyMemberVo>> groupMembers(@RequestParam("groupBuyOrderId") Long groupBuyOrderId, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        if (appLoginUser == null || appLoginUser.getUserId() == null) {
            Throw.isBusinessException("请先登录");
        }
        GroupMembersQueryDto groupMembersQueryDto = new GroupMembersQueryDto();
        groupMembersQueryDto.setGroupBuyOrderId(groupBuyOrderId);
        groupMembersQueryDto.setUserId(appLoginUser.getUserId());
        groupMembersQueryDto.setViewEnrollInfo(Boolean.TRUE);
        return orderApi.groupMembers(groupMembersQueryDto);
    }

    @ApiOperation(value = "报名详情（报名订单）")
    @ApiResponse(response = AppOrderEnrollActiveDetail.class, code = 200, message = "接口返回对象参数")
    @GetMapping("/orderEnrollActiveDetail")
    public Result<AppOrderEnrollActiveDetail> appOrderEnrollActiveDetail(AppOrderEnrollActiveDetailDto appOrderEnrollActiveDetailDto,
                                                                         @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        BusinessInfo businessInfo = appLoginUser.getUserInfo().getBusinessInfo();
        if (businessInfo != null) {
            appOrderEnrollActiveDetailDto.setBusinessId(businessInfo.getId());
        }

        appOrderEnrollActiveDetailDto.setUserId(appLoginUser.getUserId());
        return orderApi.appOrderEnrollActiveDetail(appOrderEnrollActiveDetailDto);
    }

    // 取消订单(待支付状态，直接取消，更新状态；待核销状态，直接取消，立即到账，更新状态)
    @ApiOperation(value = "取消订单")
    @ApiImplicitParam(name = "CancelOrderDto", value = "实体", paramType = "body", dataType = "cancelOrderDto")
    @PostMapping("/cancelOrder")
    public Result<Boolean> cancelOrder(@RequestBody CancelOrderDto cancelOrderDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        cancelOrderDto.setUserId(appLoginUser.getUserId());
        return orderApi.cancelOrder(cancelOrderDto);
    }

    // 确认参与
    @ApiOperation(value = "确认参与")
    @ApiImplicitParam(name = "ConfirmJoinDto", value = "实体", paramType = "body", dataType = "confirmJoinDto")
    @PostMapping("/confirmJoin")
    public Result<Boolean> confirmJoin(@RequestBody ConfirmJoinDto confirmJoinDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        confirmJoinDto.setUserId(appLoginUser.getUserId());
        return orderApi.confirmJoin(confirmJoinDto);
    }

    @ApiOperation(value = "获取订单核销二维码")
    @ApiImplicitParam(name = "verifyCode", value = "核销码", paramType = "query", dataType = "String")
    @GetMapping("/getVerifyCodeImg")
    public Result<String> getVerifyCode(String verifyCode) {
        return ResultGenerator.success(qrCodeBiz.getQrCode(verifyCode));
    }

    @ApiOperation(value = "获取最近10个订单用户头像（气泡）")
    @GetMapping("/getLastAvatar")
    public Result<List<String>> getLastAvatar() {
        return orderApi.getLastAvatar(10);
    }

    @ApiOperation(value = "待成团订单列表（可直接参团）")
    @GetMapping("/pendingGroupOrders")
    public Result<List<PendingGroupOrderVo>> listPendingGroupBuyOrders(@RequestParam("id") Long activeId, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        Long userId = null;
        if (appLoginUser != null) {
            userId = appLoginUser.getUserId();
        }
        return orderApi.listPendingGroupBuyOrders(activeId, userId);
    }

    @ApiOperation(value = "拼团 - 零元开团")
    @PostMapping("/createZeroGroupBuyOrder")
    public Result<Long> createZeroGroupBuyOrder(@RequestBody CreateZeroGroupBuyOrderDto createZeroGroupBuyOrderDto, @ApiIgnore @LoginUser AppLoginUser appLoginUser) {
        if (appLoginUser == null || appLoginUser.getUserId() == null) {
            Throw.isBusinessException("请先登录");
        }
        createZeroGroupBuyOrderDto.setUserId(appLoginUser.getUserId());
        return orderApi.createZeroGroupBuyOrder(createZeroGroupBuyOrderDto);
    }

}
